package org.yy.service.impl;

import org.apache.commons.lang.time.DateUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.yy.dao.AuthCodeDao;
import org.yy.dao.TokenDao;
import org.yy.dao.UserDao;
import org.yy.pojo.AuthCode;
import org.yy.pojo.Token;
import org.yy.pojo.User;
import org.yy.service.UserService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    TokenDao tokenDao;

    @Autowired
    AuthCodeDao authCodeDao;


    /**
     * @param email
     * @param password
     * @param code
     * @return 根据 邮箱 密码 验证码 注册 返回 true/false
     */
    @Override
    public Boolean register(String email, String password, String code) {

        // 判断是否已经注册
        if (isRegistered(email)) {
            return false;
        }

        User user = new User(email, password);
        User save = userDao.save(user);
        return !(save == null);
    }


    /**
     * @param email
     * @return 查询Email 是否已经注册
     */
    @Override
    public Boolean isRegistered(String email) {
        User user = new User(email);
        Example<User> of = Example.of(user);
        Optional<User> one = userDao.findOne(of);
        return one.isPresent();
    }

    /**
     * @param email
     * @param password
     * @return 根据邮箱 和密码登录 返回 true/false
     */
    @Override
    public String login(String email, String password, HttpServletRequest request, HttpServletResponse response) {
        User user = new User(email, password);
        Example<User> of = Example.of(user);
        Optional<User> one = userDao.findOne(of);

        if (one.isPresent()) {
            System.out.println("用户密码正确");
            String tokenValue = UUID.randomUUID().toString();
            Token token = new Token(email, tokenValue);
            Token save = tokenDao.save(token);
            Cookie cookie = new Cookie("token", tokenValue);
            response.addCookie(cookie);
            System.out.println("Token保存成功" + save);
        } else {
            System.out.println("用户密码错误");
        }

        return one.isPresent() ? one.get().getEmail() : "";
    }


    /**
     * @param token
     * @return 根据token查询邮箱
     */
    @Override
    public String info(String token) {
        Token token1 = new Token();
        token1.setToken(token);
        Example<Token> of = Example.of(token1);
        Optional<Token> one = tokenDao.findOne(of);
        return one.isPresent() ? one.get().getEmail() : "";
    }

}
